package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.sun.deploy.ui.DialogTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("添加菜品为: {}", dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("添加菜品成功");
    }

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page : {}, pageSize : {}, name : {}", page, pageSize, name);

        //创建分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //创建条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        lambdaQueryWrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(dishPage, lambdaQueryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> dishList = dishPage.getRecords();
        //遍历dishList集合,获取菜品分类id并查询,并赋值给disDtoList集合
        List<DishDto> dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //拷贝对象
            BeanUtils.copyProperties(item, dishDto);
            //查询菜品分类id
            Long categoryId = item.getCategoryId();
            //根据菜品分类id查询菜品分类对象
            Category category = categoryService.getById(categoryId);
            //判断菜品分类对象是否为空
            if (category != null) {
                //获取菜品分类名称
                String categoryName = category.getName();
                //赋值
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        //给dishDtoPage的records属性赋值
        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
    }

    /**
     * 根据菜品id查询数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        log.info("查询菜品id为: {}", id);

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    /**
     * 修改菜品数据
     *
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("修改数据为: {}", dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        return R.success("修改菜品成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     *
     * @param dish
     * @return
     */
    //@GetMapping("/list")
    public R<List<Dish>> list2(Dish dish) {
        log.info("查询的菜品分类id为 : {}", dish.getCategoryId());

        Long categoryId = dish.getCategoryId();

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据categoryId查询菜品
        lambdaQueryWrapper.eq(categoryId != null, Dish::getCategoryId, categoryId);
        //添加菜品起售状态条件
        lambdaQueryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(lambdaQueryWrapper);

        return R.success(dishList);
    }

    /**
     * 根据条件查询对应的菜品数据
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        log.info("查询的菜品id为 : {}", dish.getCategoryId());

        Long categoryId = dish.getCategoryId();

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据categoryId查询菜品
        lambdaQueryWrapper.eq(categoryId != null, Dish::getCategoryId, categoryId);
        //添加菜品起售状态条件
        lambdaQueryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(lambdaQueryWrapper);

        List<DishDto> dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Category category = categoryService.getById(item.getCategoryId());

            if (category != null){
                dishDto.setCategoryName(category.getName());
            }

            //获取菜品id
            item.getId();

            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();

            queryWrapper.eq(DishFlavor::getDishId,item.getId());

            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);

            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        /*List<DishDto> dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            //获取菜品id
            Long categoryId1 = item.getCategoryId();

            //查询对应菜品id的菜品对象获取到菜品的name
            Category category = categoryService.getById(categoryId1);
            //给disDto中categoryName属性赋值
            dishDto.setCategoryName(category.getName());

            return dishDto;
        }).collect(Collectors.toList());

        if(dish.getId()!= null){
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(dish.getId() != null,DishFlavor::getDishId,dish.getId());

            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);

            if (dishFlavorList != null){
                dishDtoList = dishDtoList.stream().map((item) -> {
                    item.setFlavors(dishFlavorList);

                    return item;
                }).collect(Collectors.toList());

                return R.success(dishDtoList);
            }
        }
*/
        return R.success(dishDtoList);
    }

    /**
     * 删除菜品信息
     *
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("删除菜品的id: {}",ids);

        dishService.removeWithFlavor(ids);

        return R.success("菜品删除成功");
    }

    /**
     * 修改菜品的状态
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@RequestParam List<Long> ids,@PathVariable Integer status){
        log.info("修改菜品状态的id: {},status: {}",ids,status);

        /*LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(ids!=null,Dish::getId,ids);
        updateWrapper.set(status != null,Dish::getStatus,status);*/

        dishService.updateWithSetmeal(ids,status);

        return R.success("修改成功");
    }
}
